package com.mcc.web.controller.system;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.mcc.common.exception.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.mcc.common.annotation.Log;
import com.mcc.common.constant.UserConstants;
import com.mcc.common.core.controller.BaseController;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.core.domain.entity.SysRole;
import com.mcc.common.core.domain.entity.SysUser;
import com.mcc.common.core.domain.model.LoginUser;
import com.mcc.common.core.page.TableDataInfo;
import com.mcc.common.enums.BusinessType;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.ServletUtils;
import com.mcc.common.utils.StringUtils;
import com.mcc.common.utils.poi.ExcelUtil;
import com.mcc.framework.web.service.TokenService;
import com.mcc.system.service.ISysPostService;
import com.mcc.system.service.ISysRoleService;
import com.mcc.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @author gxy
 */
@Api(tags = "用户")
@ApiSort(17)
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @ApiOperation("获取用户列表")
    @ApiOperationSupport(order = 1)
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public AjaxResult<TableDataInfo<SysUser>> list(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @ApiOperation("获取用户列表(分页)")
    @ApiOperationSupport(order = 2)
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/page")
    public AjaxResult<TableDataInfo<SysUser>> page(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @ApiOperation("根据用户编号获取详细信息")
    @ApiOperationSupport(order = 3)
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/get/{userId}")
    public AjaxResult getInfo(@PathVariable Long userId) {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("roles", roleService.selectRoleList(null));
        data.put("posts", postService.selectPostList(null));
        data.put("user", userService.selectUserById(userId));
        data.put("postIds", postService.selectPostListByUserId(userId));
        data.put("roleIds", roleService.selectRoleObjsByUserId(userId));
        return AjaxResult.success(data);
    }

    @ApiOperation("新增用户")
    @ApiOperationSupport(order = 4)
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        return toAjax(userService.insertUser(user));
    }

    @ApiOperation("修改用户")
    @ApiOperationSupport(order = 5)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (!userService.checkUserNameUnique(user)) {
            throw new CustomException("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    @ApiOperation("删除用户")
    @ApiOperationSupport(order = 6)
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    @ApiOperation("重置密码")
    @ApiOperationSupport(order = 7)
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    @ApiOperation("状态修改")
    @ApiOperationSupport(order = 8)
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @ApiOperation("获取角色和职位列表")
    @ApiOperationSupport(order = 9)
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/get")
    public AjaxResult getRoleAndPost() {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("roles", roleService.selectRoleList(null));
        data.put("posts", postService.selectPostList(null));
        return AjaxResult.success(data);
    }
}
